package com.strawcom.charmring.ui;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.kymjs.kjframe.KJBitmap;
import org.kymjs.kjframe.utils.SystemTool;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.android.volley.Request.Method;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool;
import com.bumptech.glide.load.resource.bitmap.BitmapTransformation;
import com.strawcom.charmring.App;
import com.strawcom.charmring.BaseActivity;
import com.strawcom.charmring.C;
import com.strawcom.charmring.R;
import com.strawcom.charmring.bean.Rank;
import com.strawcom.charmring.bean.http.BaseResponse;
import com.strawcom.charmring.bean.http.RankRequest;
import com.strawcom.charmring.bean.http.RankResponse;
import com.strawcom.charmring.util.HttpUtil;
import com.strawcom.charmring.util.HttpUtil.ResponeListener;
import com.strawcom.charmring.util.LogUtil;
import com.strawcom.charmring.util.ViewUtil;
import com.strawcom.charmring.view.TitleView;

@SuppressLint("SimpleDateFormat")
public class ExerciseRankActivity extends BaseActivity {

	private ListView listView, listView2;
	private final List<Rank> timelist = new ArrayList<Rank>();
	private final List<Rank> calorielist = new ArrayList<Rank>();
	private TitleView titleView;
	
	private TextView  txNoneData;
	private TextView txEnergy, txTime;
	private View layEnergy, layTime;
	private static final int INDEX_ENERGY = 1;
	private static final int INDEX_TIME  = 2;
	private int selectedIndex = INDEX_ENERGY;

	@Override protected void onCreate(Bundle savedInstanceState) {
		setContentView(R.layout.activity_exercise_rank);
		super.onCreate(savedInstanceState);

		titleView = (TitleView) findViewById(R.id.title_view);
		titleView.setTitleText(R.string.title_rank);
		
		listView = (ListView) findViewById(R.id.listView);
		listView.setAdapter(adapter);
		listView.setVisibility(View.GONE);
		
		listView2 = (ListView) findViewById(R.id.listView2);
		listView2.setAdapter(adapter2);
		listView2.setVisibility(View.GONE);
		
		layEnergy = findViewById(R.id.lay_energy);
		layTime = findViewById(R.id.lay_time);
		layEnergy.setOnClickListener(onTypeChangeClickListener);
		layTime.setOnClickListener(onTypeChangeClickListener);
				
		txEnergy = (TextView) findViewById(R.id.tx_energy);
		txEnergy.setTextColor(0xfffafb86);
		txTime = (TextView) findViewById(R.id.tx_time);
		
		txNoneData =(TextView) findViewById(R.id.tx_none_data);
		txNoneData.setTypeface(App.i().tfYouYuan);
		txNoneData.setText(R.string.loading_data);
			
		queryData();
	}
	
	private android.view.View.OnClickListener onTypeChangeClickListener = new View.OnClickListener() {
		@Override public void onClick(View v) {
			txEnergy.setTextColor(0xffffffff);
			txTime.setTextColor(0xffffffff);
			switch (v.getId()) {
			case R.id.lay_energy:
				selectedIndex = INDEX_ENERGY;
				txEnergy.setTextColor(0xfffafb86);
				listView.setVisibility(View.VISIBLE);
				listView2.setVisibility(View.GONE);
				txNoneData.setText(calorielist.size() == 0 ? getString(R.string.none_data) : "");	
				txNoneData.setVisibility(calorielist.size() == 0  ? View.VISIBLE :View.GONE);
				break;
			case R.id.lay_time:
				selectedIndex = INDEX_TIME;
				txTime.setTextColor(0xfffafb86);
				listView.setVisibility(View.GONE);
				listView2.setVisibility(View.VISIBLE);
				txNoneData.setText(timelist.size() == 0 ? getString(R.string.none_data) : "");
				txNoneData.setVisibility(timelist.size() == 0  ? View.VISIBLE :View.GONE);
				break;
			}
		}
	};
	
	private void queryData(){
		txNoneData.setText(R.string.loading_data);
		
		RankRequest rankRequest=new RankRequest();
		rankRequest.msgid=C.request_msgid_get_sports_ranking;
	
		
		SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMdd");
		rankRequest.date=sdf.format(new Date(System.currentTimeMillis() - 24 * 3600000));
		
		HttpUtil.requestJson(Method.GET, rankRequest, new ResponeListener() {
			
			@Override
			public void onResponse(BaseResponse response, String resultStr) {
				RankResponse rankResponse=HttpUtil.gson.fromJson(resultStr, RankResponse.class);
			
				timelist.clear();
				if(rankResponse.ranktimetbl != null){
					timelist.addAll(rankResponse.ranktimetbl);
				}
				adapter2.notifyDataSetChanged();
				
				calorielist.clear();
				if(rankResponse.rankcalorietbl != null){
					calorielist.addAll(rankResponse.rankcalorietbl);
				}
				adapter.notifyDataSetChanged();
				
				if(selectedIndex == INDEX_ENERGY){
					listView.setVisibility(View.VISIBLE);
					listView2.setVisibility(View.GONE);
					txNoneData.setText(calorielist.size() == 0 ? getString(R.string.none_data) : "");
					txNoneData.setVisibility(calorielist.size() == 0  ? View.VISIBLE :View.GONE);
				} else if(selectedIndex == INDEX_TIME) {
					listView.setVisibility(View.GONE);
					listView2.setVisibility(View.VISIBLE);
					txNoneData.setText(timelist.size() == 0 ? getString(R.string.none_data) : "");
					txNoneData.setVisibility(timelist.size() == 0  ? View.VISIBLE :View.GONE);
				}
			}
			
			@Override
			public void onErrorResponse(Exception error) {
				txNoneData.setText(SystemTool.checkNet(ExerciseRankActivity.this) ? R.string.request_error : R.string.net_error);
			}
		});
	}

	private BaseAdapter adapter = new BaseAdapter() {
		class ViewHolder {
			ImageView imgHead;
			TextView txNick, txInfo,txRank;
		}

		@Override public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder viewHolder;
			if (convertView != null) {
				viewHolder = (ViewHolder) convertView.getTag();
			}
			else {
				viewHolder = new ViewHolder();
				convertView = LayoutInflater.from(context).inflate(R.layout.list_content_exercise_rank, null);
				viewHolder.imgHead = (ImageView) convertView.findViewById(R.id.img_head);
				viewHolder.txRank = (TextView) convertView.findViewById(R.id.tx_rank);
				viewHolder.txNick = (TextView) convertView.findViewById(R.id.tx_nick);
				viewHolder.txInfo = (TextView) convertView.findViewById(R.id.tx_info);
				convertView.setTag(viewHolder);
				
				ViewUtil.changeFontsStyle(convertView, ExerciseRankActivity.this);
			}
			final Rank r = calorielist.get(position);
			
			viewHolder.txNick.setText(r.name);
			viewHolder.txInfo.setText(String.format(getString(R.string.exercise_record_energy),  String.format("%.1f",r.calorie)));
			
			viewHolder.txRank.setText(String.valueOf(position + 1));
			
			Glide.with(parent.getContext()).load(HttpUtil.url_img + r.regicon).crossFade().centerCrop()
				.transform(new GlideCircleTransform(ExerciseRankActivity.this)).into(viewHolder.imgHead);

			return convertView;
		}

		@Override public int getCount() {
			return calorielist.size();
		}

		@Override public Object getItem(int position) {
			return calorielist.get(position);
		}

		@Override public long getItemId(int position) {
			return position;
		}
	};
	
	private BaseAdapter adapter2 = new BaseAdapter() {
		class ViewHolder {
			ImageView imgHead;
			TextView txNick, txInfo,txRank;
		}

		@Override public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder viewHolder;
			if (convertView != null) {
				viewHolder = (ViewHolder) convertView.getTag();
			}
			else {
				viewHolder = new ViewHolder();
				convertView = LayoutInflater.from(context).inflate(R.layout.list_content_exercise_rank, null);
				viewHolder.imgHead = (ImageView) convertView.findViewById(R.id.img_head);
				viewHolder.txRank = (TextView) convertView.findViewById(R.id.tx_rank);
				viewHolder.txNick = (TextView) convertView.findViewById(R.id.tx_nick);
				viewHolder.txInfo = (TextView) convertView.findViewById(R.id.tx_info);
				convertView.setTag(viewHolder);
				
				ViewUtil.changeFontsStyle(convertView, ExerciseRankActivity.this);
			}
			final Rank r = timelist.get(position);
			
			viewHolder.txNick.setText(r.name);
			int time = Integer.parseInt(r.time);
			String wayInfo = time > 60 ? getString(R.string.exercise_record_way, "",
					time / 60, time % 60) : getString(R.string.exercise_record_way_1,
					"", time % 60);
			wayInfo = wayInfo.replace(getString(R.string.exercise_record_way_1), "");
			viewHolder.txInfo.setText(wayInfo);
			
			viewHolder.txRank.setText(String.valueOf(position + 1));
			
			Glide.with(parent.getContext()).load(HttpUtil.url_img + r.regicon).crossFade().centerCrop()
			.transform(new GlideCircleTransform(ExerciseRankActivity.this)).into(viewHolder.imgHead);

			return convertView;
		}

		@Override public int getCount() {
			return timelist.size();
		}

		@Override public Object getItem(int position) {
			return timelist.get(position);
		}

		@Override public long getItemId(int position) {
			return position;
		}
	};
	
	
	static class GlideCircleTransform extends BitmapTransformation {
	    public GlideCircleTransform(Context context) {
	        super(context);
	    }

	    @Override protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {
	        return circleCrop(pool, toTransform);
	    }

	    private static Bitmap circleCrop(BitmapPool pool, Bitmap source) {
	        if (source == null) return null;

	        int size = Math.min(source.getWidth(), source.getHeight());
	        int x = (source.getWidth() - size) / 2;
	        int y = (source.getHeight() - size) / 2;

	        // TO DO this could be acquired from the pool too
	        Bitmap squared = Bitmap.createBitmap(source, x, y, size, size);

	        Bitmap result = pool.get(size, size, Bitmap.Config.ARGB_8888);
	        if (result == null) {
	            result = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
	        }

	        Canvas canvas = new Canvas(result);
	        Paint paint = new Paint();
	        paint.setShader(new BitmapShader(squared, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP));
	        paint.setAntiAlias(true);
	        float r = size / 2f;
	        canvas.drawCircle(r, r, r, paint);
	        return result;
	    }

	    @Override public String getId() {
	        return getClass().getName();
	    }
	}
}
